import axios from "axios"
import TokenService from "./token.service.js"
import GlobalConfig from "../config.js";

const httpClient = axios.create({
    baseURL: import.meta.env.VUE_APP_API || 'http://testapi.local:8204/',
    timeout: 15000,
    headers: {"Content-Type": "application/json"},
})

const authInterceptor = async (config) => {
    const token = TokenService.getToken()
    if (token) {
        config.headers['Authorization'] = 'Bearer ' + token;
    }
    return config;
}

const errorAuthInterceptor = (error) => {
    return Promise.reject(error);
}

httpClient.interceptors.request.use(authInterceptor, errorAuthInterceptor);

httpClient.interceptors.response.use(
    response => {
        switch(response.status) {
            case 200:
                // yay!
                break;
            // any other cases
            default:
            // default case
        }
        return response
    },

    async (error) => {
        const config = error?.config;
        if (error.response) {
            switch(error.response.status) {
                case 401:
                    if (!config._retry && TokenService.getRefreshToken()) {
                        config._retry = true
                        try {
                            await httpClient.post('oauth2/token', {
                                grant_type: 'refresh_token',
                                client_id: GlobalConfig.ci,
                                client_secret: GlobalConfig.cs,
                                refresh_token: TokenService.getRefreshToken(),
                            }).then(response => {
                                TokenService.setUser(response.data)
                                config.headers['Authorization'] = 'Bearer ' + TokenService.getToken();
                            })
                            return httpClient(config)
                        } catch (_error) {
                            if (window.location.pathname !== '/login') {
                                document.location.href = '/login';
                            }
                        }
                    } else if (window.location.pathname !== '/login') {
                        document.location.href = '/login';
                    }
                    break
                case 404:
                case 500:
                    if (!config._retry) {
                        config._retry = false;
                        return Promise.reject(error)
                    }
                    break
                default:
            }
        }
        return Promise.reject(error)
    }
)

export default httpClient
